'''
Author: ljkt
Version: 1.1
Date: 2025-01-04 16:40:52
LastEditors: ljkt
LastEditTime: 2025-01-09 22:12:34
Description: 
'''
'''
Author: ljkt
Version: 1.1
Date: 2025-01-04 12:32:12
LastEditors: ljkt
LastEditTime: 2025-01-04 19:01:28
Description: 
'''
# -*- coding: utf-8 -*-
import os
import re
# pyinstaller -F 头文件路径设置.py
# 示例调用函数并打印结果
print("VER :2025-01-09")
from fnmatch import fnmatch  # 导入fnmatch用于支持通配符匹配
def find_files(start_dir='.', filename_pattern=None):
    """
    在指定目录及其子目录中查找符合给定模式的文件，并返回其绝对路径列表。

    参数:
    start_dir (str): 开始遍历的目录，默认为当前目录 ('.')。
    filename_pattern (str): 文件名模式（可以包含通配符），例如 'hal.h' 或 '*.h'。

    返回:
    list: 包含所有找到文件的绝对路径的列表。
    """
    if not filename_pattern:
        raise ValueError("filename_pattern 不能为空")

    found_files = []
    abs_path=filename_pattern
    for root, dirs, files in os.walk(start_dir):
        
        for file in files:
            if file.endswith((filename_pattern)):
                abs_path = os.path.abspath(os.path.join(root, file))
                found_files.append(abs_path)
                return abs_path
    
    return abs_path
def starts_with_slash(line):
    """
    检查给定行的第一个非空字符是否为斜杠 '/'。

    参数:
    line (str): 要检查的行。

    返回:
    bool: 如果第一个非空字符是斜杠，则返回 True；否则返回 False。
    """
    # 去除行首的空白字符
    stripped_line = line.lstrip()
    
    # 检查第一个字符是否为斜杠
    return stripped_line.startswith('/')


# search_filename = 'hal.h'  # 可以更改为你想要查找的文件名或模式
# found_files = find_files('.', search_filename)

# if found_files:
#     for path in found_files:
#         print(f"Found '{search_filename}': {path}")
# else:
#     print(f"No '{search_filename}' file found.")


def wirte_abs_path(abs_path=1):
    encodings_to_try = ['utf-8', 'gb2312', 'gbk']
    for root, dirs, files in os.walk('.'):
        cnt=0;
        if '.history' in dirs:
            dirs.remove('.history')  # 这会告诉 os.walk() 不要进入 .history 目录
        for file in files:
            if file.endswith(('.c', '.h')):
                new_lines = []
                file_path = os.path.join(root, file)
                # print(f"正在检查文件 {file_path}")
                for encoding in encodings_to_try:
                    try:
                        with open(file_path, 'r', encoding=encoding) as f:
                            lines = f.readlines()
                            for line in lines:
                                if 'include' in line and '.h' in line and '"' in line and False==starts_with_slash(line):
                                    if any(keyword in line for keyword in ["App_", "Dev_", "Hal_", "Drv_", "Common_"]):
                                        print(f"正在检查文件路径 {file_path} 行内容 {line}",cnt)
                                        cnt=cnt+1
                                        end_indexes = [m.start() for m in re.finditer(r'\.h"', line)]
                                        for end_index in end_indexes:
                                            start_index = 0
                                            for char_index in range(end_index, -1, -1):
                                                if line[char_index] in ['"', '/', '\\']:
                                                    start_index = char_index + 1
                                                    name=line[start_index:end_index + 2]
                                                    if abs_path==1:
                                                        
                                                        abs_name=find_files('.', name)
                                                        abs_name = f'#include "{abs_name}"\n'
                                                        new_lines.append(abs_name)
                                                        print(abs_name)
                                                    else:
                                                        no_abs_name = f'#include "{name}"\n'
                                                        new_lines.append(no_abs_name)                                                        
                                                        print(no_abs_name)
                                                    break
                                    else:
                                        new_lines.append(line)

                                else:
                                    new_lines.append(line)
                        with open(file_path, 'w', encoding=encoding) as f:
                            f.writelines(new_lines)                                                

                        break
                    except UnicodeDecodeError:
                        continue
                else:
                    print(f"未能成功解码文件 {file_path}")
while True:
    answer = input("是否添加绝对地址(y/n?): ")
    if answer.lower() == 'y':
        print("你选择了添加绝对地址，后续可编写添加地址的逻辑代码")
        wirte_abs_path(1)
    elif answer.lower() == 'n':
        print("你选择了不添加绝对地址，继续后续其他逻辑")
        wirte_abs_path(0)
    else:
        print("输入不合法，请输入'y' 或者 'n'")
